import json
import re

from django.contrib.auth import login
from django.http import JsonResponse, HttpRequest
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django_redis import get_redis_connection
from itsdangerous import TimedSerializer

from apps.oauth.models import OAuthQQUser
from apps.users.models import User
from meiduo_mall.settings import dev

# Create your views here.
class QQLoginUrlView(View):
    def get(self, request):
        qq = OAuthQQ(client_id=dev.QQ_CLIENT_ID,
                     client_secret=dev.QQ_CLIENT_SECRET,
                     redirect_uri=dev.QQ_REDIRECT_URI,
                     state='None')
        login_url=qq.get_qq_url()
        return JsonResponse({'code':0, 'errmsg':'ok','login_url':login_url})

class OauthQQView(View):
    def get(self, request: HttpRequest):
        code = request.GET.get('code')
        if code is None:
            return JsonResponse({'code':400, 'errmsg':'code is missing'})
        qq = OAuthQQ(client_id=dev.QQ_CLIENT_ID,
                     client_secret=dev.QQ_CLIENT_SECRET,
                     redirect_uri=dev.QQ_REDIRECT_URI,
                     state='None')
        token_id=qq.get_access_token(code)
        open_id=qq.get_open_id(token_id)
        from apps.oauth.utils import generic_openid
        access_token = generic_openid(open_id)
        try:
            qquser=OAuthQQUser.objects.get(openid=open_id)
        except Exception:
            return JsonResponse({'code': 400, 'errmsg':'QQ not bind', 'access_token': access_token})
        else:
            login(request, qquser.user)
            response = JsonResponse({'code': 0, 'errmsg':'ok'})
            response.set_cookie('username', qquser.user.username)
            return response

    def post(self, request):
        # 1 get arms
        data: dict=json.loads(request.body.decode())
        mobile=data.get('mobile')
        password=data.get('password')
        sms_code=data.get('sms_code')
        access_token=data.get('access_token')
        # 2.1
        if not all([mobile, password, sms_code, access_token]):
            return JsonResponse({'code': 400, 'errmsg': 'arms is miss'})
        from apps.oauth.utils import check_access_token
        openid=check_access_token(access_token)
        if openid is None:
            return JsonResponse({'code': 400, 'errmsg': 'openid is error'})
        # 2.2
        if not re.match('1[345789]\d{9}', mobile):
            return JsonResponse({'code': 400, 'errmsg': 'mobile is not allowed'})
        # 2.3 sms_code
        redis_conn=get_redis_connection('code')
        redis_sms_code=redis_conn.get(mobile)
        if redis_sms_code is None:
            return JsonResponse({'code': 400, 'errmsg': 'sms_code is timeout'})
        if redis_sms_code.decode() != sms_code:
            return JsonResponse({'code': 400, 'errmsg': 'sms_code is error'})
        # 3
        try:
            user = User.objects.get(mobile__exact=mobile)
        # not have acct
        except Exception:
            user=User.objects.create_user(username=mobile,mobile=mobile,password=password)
        # have acct
        else:
            # check password
            # password error
            if not user.check_password(password):
                return JsonResponse({'code':0, 'errmsg':'acct or password is error'})

        OAuthQQUser.objects.create(user=user, openid=openid)
        login(request, user)
        response = JsonResponse({'code': 0, 'errmsg': 'ok'})
        response.set_cookie('username', user.username)
        return  response






